
#include "StdAfx.h"
#include "ODBC_DBError.h"

ODBC_DBError::ODBC_DBError(){	
	nativeError_ = 0;
	disconnect_ = false;
}

ODBC_DBError::~ODBC_DBError(){
}

void ODBC_DBError::reset(){
	DBError::reset();

	nativeError_ = 0;	
}

int ODBC_DBError::set_error( DBSession* session, void* data, \
		const char* error_query, const char* error_method, const int error_line )
{	
	reset();

	if( error_method )
		error_method_ = error_method;

	if( error_query )
		error_query_ = error_query;

	SQLRETURN ret;	
	SQLCHAR msg[ DEF_ERROR_STR_SIZE ];
	SQLSMALLINT i = 1;
	SQLSMALLINT size = 0;	
	SQLHANDLE hstmt = (SQLHANDLE)data;
	SQLCHAR state[ DEF_ERROR_STR_CODE_SIZE ];
	
	memset( msg, 0, sizeof(SQLCHAR) * DEF_ERROR_STR_SIZE );
	
	while( ( ret = ::SQLGetDiagRec( SQL_HANDLE_STMT, hstmt, i, state, &nativeError_, \
		msg, sizeof(SQLCHAR) * DEF_ERROR_STR_SIZE, &size ) ) != SQL_NO_DATA )
	{
		if( ret == SQL_INVALID_HANDLE )
			break;

		if( size )
			error_msg_ = (char*)msg;
		else
			error_msg_ = "none";

		error_state_ = (char*)state;
		error_code_ = nativeError_;

		if( ( strcmp( (const char*)state, "08S01" ) == 0 ) || \
			( strcmp( (const char*)state, "S1T00" ) == 0 ) || \
			( strcmp( (const char*)state, "08003" ) == 0 ) || \
			( strcmp( (const char*)state, "S1000" ) == 0 ) || \
			( strcmp( (const char*)state, "01000" ) == 0 )
		  )
		{
			disconnect_ = true;
		}

		// sqlserver shutdown progress
		if( error_code_ == 6002 )
			disconnect_ = true;

		i++;
	}
	
	return i;
}

bool ODBC_DBError::isDisconnect(){
	return disconnect_;
}
